package employee.ejb.management;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import authentication.ejb.usermanagement.User;
import model.Excursion;
import model.ExcursionPersTP;
import model.ExcursionPredTP;
import model.GetEntities;
import model.Hotel;
import model.MeanOfTransportation;
import model.PersonalizedTP;
import model.PredefinedTP;
import common.Filter;
import common.IPredicate;
import common.OperationCallback;
import dtos.ExcursionDTO;
import dtos.ExcursionPredTPDTO;
import dtos.HotelDTO;
import dtos.PredefinedTPDTO;


@Stateless
public class PackageMgrBean implements PackageMgr{
	
	@PersistenceContext
    private EntityManager em;
	
	private GetEntities e;
	private int id;
	
	@PostConstruct
	public void init(){
		e = new GetEntities();
	}
	
	@Override
	public void savePredTP(PredefinedTPDTO predTP, OperationCallback oc){
		if(!predTP.isValid().equals("ok"))
		{
			oc.onError(new IllegalArgumentException(predTP.isValid()));
			return;
		}
		try
		{
		PredefinedTP newPred = new PredefinedTP();
		
		Hotel hotel = e.getHotelEntity(predTP.getHotelBean()); 
		newPred.setHotelBean(hotel);
		
		MeanOfTransportation mean1 = e.getMeanOfTransportationEntity(predTP.getMeanOfTransportation1());
		newPred.setMeanOfTransportation1(mean1);
		MeanOfTransportation mean2 = e.getMeanOfTransportationEntity(predTP.getMeanOfTransportation2());
		newPred.setMeanOfTransportation2(mean2);
		
		newPred.setUser(em.find(User.class,predTP.getUser().getUsername()));
		
		em.persist(newPred);
		em.flush();
		em.refresh(newPred);
		id = newPred.getTravelID();
		}
		catch(Throwable t)
		{
			oc.onError(t);
		}
	}
	
	@Override
	public void removePredTP(int travelid) {
		PredefinedTP predTP = em.find(PredefinedTP.class,travelid);
        em.remove(predTP);
	}
	
	@Override
	public Collection<PredefinedTPDTO> getPredTPList(){
		@SuppressWarnings("unchecked")
		List<PredefinedTP> qres = em.createQuery("SELECT x FROM PredefinedTP x").getResultList();

		Collection<PredefinedTPDTO> res = new ArrayList<PredefinedTPDTO>(qres.size());
		for(PredefinedTP tp : qres)
		{
			res.add(tp.getDTO());
		}
		return res;
	}

	@Override
	public void saveExcursionPredTP(ExcursionPredTPDTO e) {
		ExcursionPredTP exc = new ExcursionPredTP();
		exc.setExcursion(em.find(Excursion.class, e.getExcursion().getExcursionID()));
		PredefinedTP tp = em.find(PredefinedTP.class, id);
		exc.setPredefinedtp(tp);
		em.persist(exc);
		
		em.refresh(tp);

		em.flush();
		em.refresh(tp);
		
	}

}
